package management.system.view.servlet;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import management.system.model.bean.GrupoDTO;
import management.system.model.bean.PerfilDTO;
import management.system.model.services.GrupoService;
import management.system.model.services.PerfilService;
import management.system.utils.Constants;
import management.system.utils.Utils;

/**
 * Servlet implementation class ServletPerfiles
 */
@WebServlet("/perfil")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB 
maxFileSize = 1024 * 1024 * 10, // 10MB
maxRequestSize = 1024 * 1024 * 50)   // 50MB

public class ServletPerfiles extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	
    public ServletPerfiles() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String metodo = request.getParameter("metodo");
		System.out.println("doGet");
		if(metodo.equals("INSERTA")){
			insertPerfiles(request, response);
		}else if(metodo.equals("EDITA")){
			updatePerfiles(request, response);
		}else if(metodo.equals("ELIMINA")){
			deletePerfiles(request, response);
		}else if(metodo.equals("BUSCA")){
			findPerfiles(request, response);
		}else{
			listPerfiles(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String metodo = request.getParameter("metodo");
		System.out.println("doPost");
		if(metodo.equals("INSERTA")){
			insertPerfiles(request, response);
		}else if(metodo.equals("EDITA")){
			updatePerfiles(request, response);
		}else if(metodo.equals("ELIMINA")){
			deletePerfiles(request, response);
		}else if(metodo.equals("BUSCA")){
			findPerfiles(request, response);
		}else{
			listPerfiles(request, response);
		}
	}

	protected void insertPerfiles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PerfilService perfilService = new PerfilService();
		PerfilDTO dto = new PerfilDTO();
		
		Integer result;
		
        String appPath = request.getServletContext().getRealPath("");
        // constructs path of the directory to save uploaded file
        String savePath = appPath + File.separator + Constants.SAVE_DIR;
        
        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }
        System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());


        String fileName = getFileName(request.getPart("fileImage"));
        request.getPart("fileImage").write(savePath + File.separator + fileName + File.separator);
       
		
		try {
			
			if(perfilService.getNombrePerfil(request.getParameter("txtNombre")).intValue() > 0){
				Constants.VALIDATE = 1;
				response.sendRedirect("jsp/nuevoPerfil.jsp");
			}else if(perfilService.getUrlPerfil(request.getParameter("txtUrl")).intValue()> 0){
				Constants.VALIDATE = 2;
				response.sendRedirect("jsp/nuevoPerfil.jsp");
			}else{
				dto.setPerfilID(Constants.usuarioDTO.getPerfilId());
				dto.setNombre(request.getParameter("txtNombre"));
				dto.setNombreCorto(request.getParameter("txtNombreCorto"));
				dto.setTipoID(Integer.parseInt(request.getParameter("cboTipo")));
				dto.setUrl(request.getParameter("txtUrl"));
				dto.setLogo(fileName);
				result = perfilService.insertPerfil(dto);
				if(result>0){
					Constants.VALIDATE = 0;
					listPerfiles(request, response);
				}
			}
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		
	}

	protected void updatePerfiles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PerfilService perfilService = new PerfilService();
		PerfilDTO dto = new PerfilDTO();
		
		Integer result;
		
        String appPath = request.getServletContext().getRealPath("");
        // constructs path of the directory to save uploaded file
        String savePath = appPath + File.separator + Constants.SAVE_DIR;
        
        File fileSaveDir = new File(savePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdir();
        }
        System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());


        String fileName = getFileName(request.getPart("fileImage"));
        request.getPart("fileImage").write(savePath + File.separator + fileName + File.separator);
       
		
		try {
			
				dto.setPerfilID(Integer.parseInt(request.getParameter("codigo")));
				dto.setPerfilID(Constants.usuarioDTO.getPerfilId());
				dto.setNombre(request.getParameter("txtNombre"));
				dto.setNombreCorto(request.getParameter("txtNombreCorto"));
				dto.setTipoID(Integer.parseInt(request.getParameter("cboTipo")));
				dto.setUrl(request.getParameter("txtUrl"));
				dto.setLogo(fileName);
				result = perfilService.updatePerfil(dto);
				if(result>0){
					Constants.VALIDATE = 0;
					listPerfiles(request, response);
				}
			
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	protected void deletePerfiles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PerfilService perfilService = new PerfilService();
		Integer result;
		
		Integer id = 
				Integer.parseInt(request.getParameter("cod"));

		try {
			result = perfilService.deletePerfil(id);
			
			if(result>0){
				listPerfiles(request, response);
			}
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	protected void findPerfiles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PerfilService perfilService = new PerfilService();
		PerfilDTO dto = new PerfilDTO();
		
		Integer id = 
				Integer.parseInt(request.getParameter("cod"));

		try {
			dto = perfilService.getPerfil(id);
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		request.setAttribute("bean", dto);
		
		RequestDispatcher rd =
				getServletContext().
				getRequestDispatcher("/jsp/editaPerfil.jsp");
			rd.forward(request, response);
	}
	
	protected void listPerfiles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		PerfilService perfilService = new PerfilService();
		ArrayList<PerfilDTO> lstPerfiles = null;
		
		String nombre = null;
		 nombre = request.getParameter("txtNombre");
		 System.out.println("Parameter:"+nombre);
		
		try {
			if(nombre!=null)
				lstPerfiles = perfilService.listPerfil(nombre);
			else
				lstPerfiles = perfilService.listPerfil("");
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		

		request.setAttribute("perfiles", lstPerfiles);
		
		getServletContext().getRequestDispatcher("/jsp/listarPerfiles.jsp").forward(request, response);
		
	}
	
    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
       
        System.out.println("content-disposition header= "+contentDisp);
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf("=") + 2, token.length()-1);
            }
        }
        return "";
    }

}
